package net.kleinhenz.questor.game;

import java.util.HashMap;
import java.util.Map;

import net.kleinhenz.questor.Questor;
import net.kleinhenz.questor.exceptions.QuestorConditionException;
import net.kleinhenz.questor.exceptions.QuestorScriptException;
import net.kleinhenz.questor.model.Condition;
import net.kleinhenz.questor.model.ExecutableBase;
import net.kleinhenz.questor.system.Script;

/**
 * Implements a lightweight condition system. 
 * 
 * @author Michael Kleinhenz, m.kleinhenz@tarent.de
 */
public class ScriptCondition extends ExecutableBase implements Condition
{
	public ScriptCondition(String code)
	{
		super(code);
	}

	@Override
	public boolean eval() throws QuestorConditionException
	{
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("player", Questor.getCurrentGame().getPlayer());
		variables.put("playerVars", Questor.getCurrentGame().getPlayer().getVariables());
		variables.put("playerItems", Questor.getCurrentGame().getPlayer().getItems());
		variables.put("game", Questor.getCurrentGame());
		try
		{
			return Script.eval(getCode(), variables);
		}
		catch (QuestorScriptException e)
		{
			throw new QuestorConditionException("Error while executing statement: " + getCode(), e);
		}
	}	
}
